import React from "react";
import { TouchableOpacity, View } from "react-native-ui-lib";
import { commonStyles } from "../../configs/commonStyle";
import NavigationBar from "../common/NavigationBar";
import BasePage from "../BasePage";
import { windowWidth } from "../../configs/platform";
import ListEmpty from "../common/ListEmpty";
import { TabBar, TabBarIndicator, TabView } from "react-native-tab-view";
import Events from "../../utils/events";
import DeliveryOrderList from "./DeliveryOrderList";
import { inject, observer } from "mobx-react";
import { NavigationEvents } from "react-navigation";
import DateFilter from "../components/DateFilter";
import moment from "moment";
import { StyleSheet, Text } from "react-native";
import { uploadError } from "../../utils/util";

/**
 * 首页
 */
@inject("userStore", "appStore")
@observer
export default class Home extends BasePage {
  constructor(props) {
    super(props);
    this.orderList = [];
    this.state = {
      index: 0,
      currentKey: 'all',
      routes: [
        { key: "all", title: "全部", value: "" },
        { key: "need", title: "待配送", value: "6" },
        { key: "transfer", title: "中转中", value: "12" },
        { key: "had", title: "配送中", value: "7" },
        { key: "reject", title: "已完成", value: "8" },
      ],
      delyStartTime: moment().format("YYYY-MM-DD"),
      delyEndTimeEnd: moment().format("YYYY-MM-DD"),
    };
  }

  componentDidMount() {
    super.componentDidMount();
    this.refreshOrderList = Events.subscribe("RefreshOrderList", () => this.loadCurrentKeyData());
  }

  loadAllData=()=>{
    this.loadData(true);
    this.state.routes.map(route => {
      if (this.orderList[route.key] && this.orderList[route.key].loadByDate) {
        this.orderList[route.key].loadByDate(this.state.delyStartTime, this.state.delyEndTimeEnd);
      }
    });
  }

  loadCurrentKeyData = () => {
    const { currentKey } = this.state;
    this.orderList[currentKey].loadByDate && this.orderList[currentKey].loadByDate(this.state.delyStartTime, this.state.delyEndTimeEnd);
  }

  componentWillUnmount() {
    super.componentWillUnmount();
    this.refreshOrderList && this.refreshOrderList.remove();
  }

  loadData = (showLoading = false) => {
    const { delyStartTime, delyEndTimeEnd } = this.state;
    if(IsNullOrEmpty(delyStartTime))
    {
      uploadError('countOrderByState查询日期为空',`${delyStartTime},${delyEndTimeEnd}`)
    }

    let params = {
      token: global.token,
      delyStartTime: `${delyStartTime} 00:00:00`,
      delyEndTimeEnd: `${delyEndTimeEnd} 23:59:59`,
      showLoading,
    };
    axios.get(api.countOrderByState, { params })
      .then(res => {
        logger("统计", res);
        this.setState({
          routes: [
            { key: "all", title: `全部(${res?.all})`, value: "" },
            { key: "need", title: `待配送(${res?.state6})`, value: "6" },
            { key: "transfer", title: `中转中(${res?.state12 || 0})`, value: "12" },
            { key: "had", title: `配送中(${res?.state7})`, value: "7" },
            { key: "reject", title: `已完成(${res?.state8})`, value: "8" },
          ],
        });

      })
      .catch(e => {
        logger("error", e);
        this.setState({
          routes: [
            { key: "all", title: "全部", value: "" },
            { key: "need", title: "待配送", value: "6" },
            { key: "transfer", title: "中转中", value: "12" },
            { key: "had", title: "配送中", value: "7" },
            { key: "reject", title: "已完成", value: "8" },
          ],
        });
      });
  };

  componentWillUnmount() {
    super.componentWillUnmount();
    this.changeTabListener && this.changeTabListener.remove();
  }

  renderTabBar = (props) => {
    return (
      <TabBar
        {...props}
        style={{ backgroundColor: "white", elevation: 0, alignSelf: "center", height: 45, marginBottom: 8 }}
        activeColor={"#F9D63B"}
        inactiveColor={"#6F6F6F"}
        scrollEnabled
        tabStyle={{ width: windowWidth / 5, paddingHorizontal: 0 }}
        labelStyle={{}}
        renderIndicator={indicatorProps => {
          const width = indicatorProps.getTabWidth(this.state.index);
          return <TabBarIndicator {...indicatorProps} width={30}
                                  style={{ left: (width - 30) / 2, backgroundColor: "#F9D63B" }} />;
        }}
      />
    );
  };

  render() {
    const { delyStartTime, delyEndTimeEnd, index } = this.state;
    return (
      <View useSafeArea style={commonStyles.body_primary}>
        <NavigationEvents onDidFocus={() => this.loadData()} />
        <NavigationBar
          title={"配送"}
          backgroundColor={"transparent"}
        />

        <View style={commonStyles.container}>
          <View row centerV>
          <DateFilter onQueryClick={(delyStartTime, delyEndTimeEnd) => this.setState({
            delyStartTime,
            delyEndTimeEnd,
          }, () => this.loadCurrentKeyData())} />
          <TouchableOpacity activeOpacity={1} throttleTime={1000} style={styles.btn} onPress={()=>this.loadCurrentKeyData()}>
            <Text style={commonStyles.text_black}>刷新</Text>
          </TouchableOpacity>
        </View>
          <TabView
            lazy
            navigationState={this.state}
            renderScene={({ route }) => <DeliveryOrderList
              ref={r => this.orderList[route.key] = r}
              refresh={() => this.loadData()}
              delyStartTime={delyStartTime}
              delyEndTimeEnd={delyEndTimeEnd} {...this.props} {...route} />}
            initialLayout={{ width: windowWidth }}
            onIndexChange={(index) => {
              const route = this.state.routes[index]
              this.setState({ currentKey: route.key, index: index }, () => this.loadCurrentKeyData())
            }}
            renderTabBar={this.renderTabBar}
            renderLazyPlaceholder={() => <ListEmpty showEmpty={true} />}
          />
        </View>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  btn: {
    width: 80,
    height: 40,
    ...commonStyles.center,
    backgroundColor: "#F9D63B",
    borderRadius: 5,
  },
})
